<?php
session_start();
if (!isset($_SESSION['user'])) {
    header('Location: index.php');
    exit;
}

$pageTitle = "个人中心";
include 'includes/functions.php';
include 'includes/header.php';

$user = $_SESSION['user'];
$userArticles = getUserArticles($user['user_id']);
$stats = getArticleStats($user['user_id']);
?>

<div class="container">
    <div class="profile-header">
        <h1>个人中心</h1>
        <p>管理你的个人信息和博客内容</p>
    </div>
    
    <div class="profile-layout">
        <!-- 侧边栏 -->
        <div class="profile-sidebar">
            <div class="profile-card">
                <div class="profile-avatar">
                    <i class="fas fa-user"></i>
                </div>
                <h3><?php echo htmlspecialchars($user['display_name'] ?? $user['username']); ?></h3>
                <p class="user-email"><?php echo htmlspecialchars($user['email'] ?? ''); ?></p>
                
                <div class="profile-stats">
                    <div class="stat-item">
                        <div class="stat-number"><?php echo $stats['total_posts'] ?? 0; ?></div>
                        <div class="stat-label">文章</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-number"><?php echo $stats['published_posts'] ?? 0; ?></div>
                        <div class="stat-label">已发布</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-number"><?php echo $stats['total_views'] ?? 0; ?></div>
                        <div class="stat-label">浏览量</div>
                    </div>
                </div>
            </div>
            
            <div class="profile-actions">
                <a href="create.php" class="btn btn-primary">
                    <i class="fas fa-plus"></i> 写新文章
                </a>
                <a href="index.php" class="btn btn-accent">
                    <i class="fas fa-home"></i> 返回首页
                </a>
            </div>
        </div>
        
        <!-- 主内容区 -->
        <div class="profile-main">
            <!-- 个人信息设置 -->
            <div class="profile-section">
                <h2>个人信息设置</h2>
                <form id="profile-form" class="profile-form">
                    <div class="form-group">
                        <label for="display-name">显示名称</label>
                        <input type="text" id="display-name" value="<?php echo htmlspecialchars($user['display_name'] ?? ''); ?>" placeholder="请输入显示名称">
                    </div>
                    
                    <div class="form-group">
                        <label for="email">邮箱地址</label>
                        <input type="email" id="email" value="<?php echo htmlspecialchars($user['email'] ?? ''); ?>" placeholder="请输入邮箱地址">
                    </div>
                    
                    <div class="form-group">
                        <label for="bio">个人简介</label>
                        <textarea id="bio" rows="4" placeholder="介绍一下自己..."><?php echo htmlspecialchars($user['bio'] ?? ''); ?></textarea>
                    </div>
                    
                    <button type="submit" class="btn btn-primary">保存个人信息</button>
                </form>
            </div>
            
            <!-- 密码修改 -->
            <div class="profile-section">
                <h2>修改密码</h2>
                <form id="password-form" class="profile-form">
                    <div class="form-group">
                        <label for="current-password">当前密码</label>
                        <input type="password" id="current-password" placeholder="请输入当前密码">
                    </div>
                    
                    <div class="form-group">
                        <label for="new-password">新密码</label>
                        <input type="password" id="new-password" placeholder="请输入新密码">
                    </div>
                    
                    <div class="form-group">
                        <label for="confirm-password">确认新密码</label>
                        <input type="password" id="confirm-password" placeholder="请再次输入新密码">
                    </div>
                    
                    <button type="submit" class="btn btn-primary">修改密码</button>
                </form>
            </div>
            
            <!-- 我的文章 -->
            <div class="profile-section">
                <div class="section-header">
                    <h2>我的文章</h2>
                    <a href="create.php" class="btn btn-small">写新文章</a>
                </div>
                
                <?php if (empty($userArticles)): ?>
                    <div class="empty-state">
                        <i class="fas fa-edit"></i>
                        <h3>还没有文章</h3>
                        <p>开始创作你的第一篇文章吧！</p>
                        <a href="create.php" class="btn">写第一篇文章</a>
                    </div>
                <?php else: ?>
                    <div class="articles-list">
                        <?php foreach ($userArticles as $article): ?>
                            <div class="article-item">
                                <div class="article-info">
                                    <h3><?php echo htmlspecialchars($article['title']); ?></h3>
                                    <div class="article-meta">
                                        <span><i class="far fa-calendar"></i> <?php echo date('Y-m-d', strtotime($article['created_at'])); ?></span>
                                        <span><i class="far fa-eye"></i> <?php echo $article['view_count']; ?>次阅读</span>
                                        <span class="status-badge <?php echo $article['status']; ?>">
                                            <?php echo $article['status'] === 'published' ? '已发布' : '草稿'; ?>
                                        </span>
                                    </div>
                                </div>
                                <div class="article-actions">
                                    <a href="detail.php?id=<?php echo $article['post_id']; ?>" class="btn btn-small">查看</a>
                                    <a href="edit.php?id=<?php echo $article['post_id']; ?>" class="btn btn-small btn-accent">编辑</a>
                                    <button class="btn btn-small btn-danger delete-article" data-id="<?php echo $article['post_id']; ?>">删除</button>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<script>
// 个人信息更新
document.getElementById('profile-form').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const displayName = document.getElementById('display-name').value.trim();
    const email = document.getElementById('email').value.trim();
    const bio = document.getElementById('bio').value.trim();
    
    if (!displayName || !email) {
        alert('显示名称和邮箱不能为空');
        return;
    }
    
    const formData = new FormData();
    formData.append('action', 'update_profile');
    formData.append('display_name', displayName);
    formData.append('email', email);
    formData.append('bio', bio);
    
    fetch('api.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert(data.message);
            location.reload();
        } else {
            alert(data.error || '更新失败');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('更新失败，请重试');
    });
});

// 密码修改
document.getElementById('password-form').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const currentPassword = document.getElementById('current-password').value;
    const newPassword = document.getElementById('new-password').value;
    const confirmPassword = document.getElementById('confirm-password').value;
    
    if (!currentPassword || !newPassword || !confirmPassword) {
        alert('所有密码字段都不能为空');
        return;
    }
    
    if (newPassword !== confirmPassword) {
        alert('新密码和确认密码不匹配');
        return;
    }
    
    if (newPassword.length < 6) {
        alert('新密码长度至少6位');
        return;
    }
    
    const formData = new FormData();
    formData.append('action', 'update_password');
    formData.append('current_password', currentPassword);
    formData.append('new_password', newPassword);
    formData.append('confirm_password', confirmPassword);
    
    fetch('api.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert(data.message);
            document.getElementById('password-form').reset();
        } else {
            alert(data.error || '密码修改失败');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('密码修改失败，请重试');
    });
});

// 删除文章
document.querySelectorAll('.delete-article').forEach(button => {
    button.addEventListener('click', function() {
        const postId = this.getAttribute('data-id');
        
        if (confirm('确定要删除这篇文章吗？此操作不可撤销。')) {
            const formData = new FormData();
            formData.append('action', 'delete_article');
            formData.append('post_id', postId);
            
            fetch('api.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert(data.message);
                    location.reload();
                } else {
                    alert(data.error || '删除失败');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('删除失败，请重试');
            });
        }
    });
});
</script>

<?php include 'includes/footer.php'; ?>